package transportP2P

import (
	"fmt"
	"gitee.com/jjawesomejj/awesome-util/helper/commonhelper"
	"gitee.com/jjawesomejj/awesomehttp/boot"
	awesomehttp "gitee.com/jjawesomejj/awesomehttp/system"
	"gitee.com/jjawesomejj/awesomehttp/system/httpContext"
	"github.com/net-byte/vtun/appConfig"
	"strconv"
	"time"
)

func StartHttpServer(httpServerPort string) {
	httpServerPortInt, err := strconv.Atoi(httpServerPort)
	if err != nil {
		panic("不是一个有效的端口号：" + httpServerPort)
	}
	app := boot.DefaultApp()
	app.Port = float64(httpServerPortInt)
	app.AddRoute(awesomehttp.Route{
		RequestMethod: awesomehttp.REQUEST_METHOD_ANY,
		Router:        "setTransport",
		RunFun: func(ctx *httpContext.HttpContext) interface{} {
			if Iface == nil {
				return map[string]interface{}{
					"error": "虚拟网卡未就绪",
				}
			}
			targetId := ctx.Get("target_id").(string)
			pointer := GetControlPointer()
			connection, err := pointer.GetTransportUdpClient(targetId, time.Second*5)
			if err != nil {
				return map[string]interface{}{
					"error": err.Error(),
				}
			}
			connection.Write([]byte(commonhelper.JsonEncode(CreateInitTarget(appConfig.GetLocalSid()))))
			manager.SetTransportUdp(targetId, connection, func(message []byte) {
				OnReadFromUdp(message, targetId)
			})
			return make(map[string]string)
		},
	})
	app.AddRoute(awesomehttp.Route{
		RequestMethod: awesomehttp.REQUEST_METHOD_ANY,
		Router:        "setTargetId",
		RunFun: func(ctx *httpContext.HttpContext) interface{} {
			if Iface == nil {
				return map[string]interface{}{
					"error": "虚拟网卡未就绪",
				}
			}
			targetId := ctx.Get("target_id").(string)
			ip, err := appConfig.HostConfManager.CreateRemoteRequestUserHost(targetId)
			if err != nil {
				return map[string]interface{}{
					"error": err.Error(),
				}
			}
			return map[string]interface{}{
				"data": ip,
			}
		},
	})
	fmt.Println("启动http控制台：" + "http://127.0.0.1:" + httpServerPort + "/setTransport")
	app.Listen()
}
